/**  
 * Copyrights@2006, Tianyuan DIC Information Co.,Ltd.
 * 文件名:    TaobaoFeeHandle.java  
 * 描述:   
 * 作者:     kaiyang
 * 版本:    1.0  
 * 创建时间:   2015年4月21日 上午9:25:26  
 *  
 * 修改历史:  
 * 日期                          作者           版本         描述  
 * ------------------------------------------------------------------  
 * 2015年4月21日      kaiyang      1.0        1.0 Version  
 */ 
package com.hp.bon.sgw.wh.channel.handler;

import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alipay.standard.model.message.StandardMessage;
import com.alipay.standard.model.message.body.QBIReqMessageBody;
import com.hp.bon.sgw.Constants;
import com.hp.bon.sgw.Constants.MessageType;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.core.BuzProcessorManager;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.channel.SoapChannel;
import com.hp.bon.sgw.core.channel.handler.IAsynCallHandler;
import com.hp.bon.sgw.domain.MessageDetail;
import com.hp.bon.sgw.threads.MessageDetailCacheManager;
import com.hp.bon.sgw.threads.TaskManager;
import com.hp.bon.sgw.wh.service.TaobaoResponseService;
import com.hp.bon.sgw.wh.service.WHConfigService;
import com.hp.ocs.diameter.message.AVP;
import com.hp.ocs.diameter.message.AVP_Grouped;
import com.hp.ocs.diameter.message.AVP_UTF8String;
import com.hp.ocs.diameter.message.AVP_Unsigned32;
import com.hp.ocs.diameter.message.AVP_Unsigned64;
import com.hp.ocs.diameter.message.InvalidAVPLengthException;
import com.hp.ocs.diameter.message.Message;

/**  
 * @ClassName: TaobaoFeeHandle   
 * @Description: TODO  
 * @author: kaiyang  
 * @date:2015年4月21日 上午9:25:26     
 */
public class TaobaoFeeHandle implements IAsynCallHandler{

	private static final Logger _log = LoggerFactory.getLogger(TaobaoFeeHandle.class);
	private PrintStream printStream;
	private WHConfigService whConfigService;
	private StandardMessage standardMessage;
	private TaobaoResponseService taobaoResponseService;
	
	
	public TaobaoFeeHandle(PrintStream printStream,WHConfigService whConfigService,StandardMessage standardMessage,TaobaoResponseService taobaoResponseService)
	{
		this.printStream = printStream;
		this.whConfigService = whConfigService;
		this.standardMessage = standardMessage;
		this.taobaoResponseService = taobaoResponseService;
	}
	
	@Override
	public int getProtocolType() {
		return 0;
	}
  
	@Override
	public void onCallResult(CallParam callParam) {
		XmlMessage ack = null;
		Object response = null;
		if (callParam.getResponse() != null) {
			response = callParam.getResponse();
		} else if (callParam.getRecvResponse() != null) {
			response = callParam.getRecvResponse();
		}
		if (response == null) {
			ack = SoapChannel.createERRAnwser(
					callParam.getSessionId(),
					callParam.getRetCode() == 3002 ? 11202 : callParam
							.getRetCode(), callParam.getResultMsg());
		} else {
			if (response instanceof Message) {// CCA -> XML
				ack = BuzProcessorManager.getInstance().convertMessageToAck(
						callParam);
			} else if (response instanceof XmlMessage) {
				ack = (XmlMessage) response;
			} else {
				_log.warn("unknown response type:"
						+ callParam.getResponse().getClass().getName());
			}
		}
		try {
			String respXML = convertResponseString((Message)response,callParam.getServiceResultCode());
			_log.info("serviceResultCode = {}",callParam.getServiceResultCode());
			_log.info("resultMsg = {}",callParam.getResultMsg());
			byte[] resp = respXML.getBytes("UTF-8");
			ack.setLength(resp.length);
			ack.setMsgTime(System.currentTimeMillis());
			printStream.write(resp);
			printStream.close();

			callParam.setResponse(ack);

			if (callParam.getRetCode() == Constants.ResultCode.SUCCESS) {// 成功的消息，请求应答入库

				MessageDetail detail = new MessageDetail();
				detail.setBusinessCallId(callParam.getBussinessCallId());
				detail.setSessionId(callParam.getSessionId());
				detail.setServiceContextId(callParam.getServiceContextId());
				detail.setMessageType(MessageType.WSA);
				detail.setDetails(ack.getDATA());
				detail.setMsgTime(new Date(ack.getMsgTime()));
				detail.setOpType("send");
				detail.setHostId(callParam.getUserName());
				MessageDetailCacheManager.getInstance().add(detail);
			}
			TaskManager.taskProcess(callParam);
			_log.info("http response(taobao) " + respXML);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


	private String convertResponseString(Message answer, int serviceResultCode)
	{
		String priKeyPath = whConfigService.getValue("ali.priKeyPath","");
		String priKeyPassword = whConfigService.getValue("ali.priKeyPassword","");
		QBIReqMessageBody messageBody = (QBIReqMessageBody)standardMessage.getMessageBody();
		String response = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd HH:mm:ss");
		String msgTime = sdf.format(new Date());
		Map<String,String> data = new HashMap<String, String>();
		if (serviceResultCode != 0) {
			if(serviceResultCode==501||serviceResultCode==508){
				data.put("type","Error");
				data.put("msgId",standardMessage.getMessageHeader().getMsgId());
				data.put("errorCode","1002");
				data.put("errorMessage","");
				data.put("msgTime",msgTime);
				response = taobaoResponseService.getResponse("taobaoError",data,priKeyPath,priKeyPassword);
			}else{
				data.put("type","Error");
				data.put("msgId",standardMessage.getMessageHeader().getMsgId());
				data.put("errorCode","1005");
				data.put("errorMessage","");
				data.put("msgTime",msgTime);
				response = taobaoResponseService.getResponse("taobaoError",data,priKeyPath,priKeyPassword);
			}
		}
		else
		{
			long acctId = 0;
			String acctName = "";
			int shouldCharge = 0;
			try {
				//service_infomation
				AVP avp = answer.find(Constants.DIAMETER_AVP_SERVICE_INFOMATION,Constants.DIAMETER_VENDOR_3GPP);
				AVP_Grouped serviceInfomation = new AVP_Grouped(avp);
				//billQueryInfomation
				avp = serviceInfomation.find(80167,Constants.DIAMETER_VENDOR_CT);
				AVP_Grouped billQueryInfomation = new AVP_Grouped(avp);
				//acct_id
				AVP acctIdAvp = billQueryInfomation.find(80107,Constants.DIAMETER_VENDOR_CT);
				if (acctIdAvp != null)
					acctId = new AVP_Unsigned64(acctIdAvp).queryValue();
				//acct_name
				AVP acctNameAvp = billQueryInfomation.find(80108,Constants.DIAMETER_VENDOR_CT);
				if (acctNameAvp != null)
					acctName = new AVP_UTF8String(acctNameAvp).queryValue();
				//Should-Charge
				AVP shouldChargeAvp = billQueryInfomation.find(80119,Constants.DIAMETER_VENDOR_CT);
				if (shouldChargeAvp != null)
					shouldCharge = new AVP_Unsigned32(shouldChargeAvp).queryValue();
			} catch (InvalidAVPLengthException e) {
				
			}
			data.put("type","QBIRes");
			data.put("msgId",standardMessage.getMessageHeader().getMsgId());
			data.put("msgTime",msgTime);
			data.put("billKey",messageBody.getBillKey());
			data.put("companyId",messageBody.getCompanyId());
			data.put("contractNo",acctId+"");
			data.put("customerName",acctName);
			data.put("billAmount",shouldCharge+"");
			
			response = taobaoResponseService.getResponse("taobaoQueryFee",data,priKeyPath,priKeyPassword);
		}
		return response;
	}
}
